<template>
    <div class="etf-container">
        <div class="top">
            <v-breadcrumbs>
                <v-breadcrumbs-item v-for="(item, index) in breadcrumbs">
                    <span  class="breadcrumbs-item long"
                        :style="{ color: `${index == 0 ? '#B1B6C6' : '#EAECEF'}` }" @click="backTo(index)">{{ item.title
                        }}</span>
                    <v-breadcrumbs-divider v-if="index == 0">
                        <v-icon class="top-breadcrumbs" icon="mdi-chevron-right"></v-icon>
                    </v-breadcrumbs-divider>
                </v-breadcrumbs-item>
            </v-breadcrumbs>
        </div>
        <div class="total">{{ name }}</div>
        <!-- <div class="c-title">
            <div class="tt t2">行为</div>
            <div class="tt t3">代币</div>
            <div class="tt t4">数量</div>
            <div class="tt t5">价值</div>
            <div class="tt t6">时间</div>
        </div> -->
        <!-- <div class="all">
            <div class="c-list" v-for="(item, i) in etfList" :class="getColor(item)">
                <div class="tt t2">{{ item.action }}</div>
                <div class="tt t3">BTC <span class="chs">{{ item.value }}</span></div>
                <div class="tt t4">({{ item.percent }}%)</div>
                <div class="tt t5">
                    <div class="rr r1">
                        <JNumber :num="item.totalBalance * BtcPrice" prefix="$" notbold></JNumber>
                    </div>
                    <div class="rr r2">
                        <JNumber :num="item.totalBalance" :prefix="item.opt" notbold></JNumber>
                    </div>
                </div>
                <div class="tt t6">{{ getTime(item.time) }}</div>
            </div>
        </div> -->

        <div class="mlist">
            <div class="m-it" v-for="item in etfList">
                <div class="mnv">
                    <div class="htd">{{ item.hash }}</div>
                    <div class="hts">{{ getTime(item.time) }}</div>
                </div>
                <div class="mitem">
                    <div class="mm1">
                        <div class="sm" v-for="i in item.showInputs">{{ i.key }}</div>
                    </div>
                    <div class="mm2">
                        <div class="sm" v-for="i in item.showInputs">{{ i.value }}</div>
                    </div>
                    <img class="mmi" src="@/assets/rarr.png" />
                    <div class="mm3">
                        <div class="sm" v-for="i in item.showOutputs">{{ i.key }}</div>
                    </div>
                    <div class="mm4">
                        <div class="sm" v-for="i in item.showOutputs">{{ i.value }}</div>
                    </div>
                </div>
                <div class="mre" @click="onMore(item)" v-if="hasMore(item)">{{ $t('message.etf.mm') }}</div>
            </div>
        </div>
        <jLoading v-if="loading"></jLoading>

        <Empty v-if="etfList.length == 0 && !loading"></Empty>
        <JPage class="jpgs" :model-value="pageInfo.current" :length="pageInfo.pages" @update:modelValue="onPage"
            :total-visible="3"></JPage>
    </div>
</template>

<script setup lang="ts">
import { URL_ETF_DETAIL, URL_ETF_TRANSACTION } from "@/comm/api";
import { get } from "@/comm/request";
import { ref, reactive, onMounted, computed } from "vue"
import { useRoute, useRouter } from "vue-router";
import jLoading from "@/components/j-loding/index.vue"
import Empty from "@/components/j-empty/index.vue"
import { useKline } from "@/stores/kline";
import { formatTimestamp } from "@/comm/format";
import JNumber from "@/components/j-number/index.vue"
import JPage from "@/components/j-page/index.vue";
import i18n from "@/locals";

const entityData = ref<any>({});
const etfList = ref<any>([]);
const router = useRouter();
const loading = ref(true)
const breadcrumbs = reactive([{
    title: i18n.global.t("message.News.info.b"),
    disabled: true,
    href: 'breadcrumbs_dashboard',
}, {
    // title: i18n.global.t("message.News.info.a"),
    title: "EFFs",
    disabled: false,
}]);

const route = useRoute();
const list = ref<any[]>([])
const name = ref("");
const pageInfo = reactive({
    current: 0,
    pages: 0,
    size: 10,
    total: 0
})

const kline = useKline();
const BtcPrice = computed(() => {
    return kline.map.find((item: any) => item.baseCurrency == 'BTC')?.lastPrice || 0
})

function getTime(t: number) {
    // return formatTimeAgo(t * 1000);
    return formatTimestamp(t * 1000)
}

const backTo = (e: any) => {
    console.log('点击', e)
    if (e == 0) {
        router.push("/");
    }
    if(e == 1){
        router.back()
    }
}

function getColor(item: any) {
    if (item.action == "Buy") {
        return "is-win"
    }
    return "is-lose";
}

function onMore(item: any) {
    item.showInputs = item.inputArr;
    item.showOutputs = item.outputArr;
}

function hasMore(item: any) {
    if (item.showInputs.length < item.inputArr.length) {
        return true;
    }

    if (item.showOutputs.length < item.outputArr.length) {
        return true;
    }
    return false;
}

const onPage = (v: number) => {
    pageInfo.current = v;
    console.log("变化", v);
    loadPage();
};

onMounted(() => {
    loadDetail();
    console.warn("BTC price", BtcPrice.value)
    if (BtcPrice.value) {
        loadPage();
    }
    else {
        setTimeout(() => {
            loadPage();
        }, 1200);
        console.warn("no BTC price")
    }
})

async function loadDetail() {
    try {
        let res: any = await get(URL_ETF_DETAIL.replace("@", route.params.id + ""));
        name.value = res.data.entityName || res.data.entityId;
        // breadcrumbs[1].title = name.value
    }
    catch (e) {
        console.log(e)
    }
    // loading.value = false;
}

function objToArray(obj: any) {
    const arr = [];
    for (let i in obj) {
        arr.push({
            key: i,
            value: obj[i].value
        })
    }
    return arr;

}


async function loadPage() {
    loading.value = true
    try {
        let res: any = await get(URL_ETF_TRANSACTION.replace("@", route.params.id + ""), { current: pageInfo.current, size: pageInfo.size });

        if (res.data?.records?.length > 0) {
            let arr = res.data.records;
            arr.forEach((item: any) => {
                item.inputArr = objToArray(item.inputs);
                item.outputArr = objToArray(item.outputs);
                item.showInputs = item.inputArr.slice(0, 2)
                item.showOutputs = item.outputArr.slice(0, 2)
            })
            etfList.value = arr;

            pageInfo.pages = res.data.pages;
            pageInfo.total = res.data.total;

        }
    }
    catch (e) {
        console.log(e)
    }
    loading.value = false;

}
function sortChange(list: any[]) {
    list.forEach((item, index) => {
        item.balance = Number(item.value) * BtcPrice.value //该单价值
        item.action = item.direction == 'out' ? 'Buy' : 'Sell'
        if (index == 0) {
            item.totalBalance = entityData.value.totalBalance * BtcPrice.value //第一条总市值 = 机构当前持仓数量 * BTC价格
        } else {
            if (list[index - 1].direction == 'out') {
                item.totalBalance = list[index - 1].totalBalance - list[index - 1].balance   //去掉本单后的价值 = 机构当前剩余持仓价值 - 该单价值
            }
            if (list[index - 1].direction == 'in') {
                item.totalBalance = list[index - 1].totalBalance + list[index - 1].balance  //去掉本单后的价值 = 机构当前剩余持仓价值 - 该单价值
            }
        }
        item.percent = ((item.balance / item.totalBalance) * 100).toFixed(2)

        if (item.action == "Sell") {
            item.percent = '-' + item.percent
            item.opt = '-';
        }
        else {
            item.opt = '+'
        }
    })
    etfList.value = list
    console.log('列表', etfList.value)
}

</script>

<style lang="less" scoped>
@import url("./detail.less");
</style>
